<template>
  <el-card class="box-card">

    <!--  新增/修改弹出框  -->
    <el-dialog
        :title="dialogTitle+'分类'"
        :visible.sync="dialogAddOrUpdate"
        width="40%"
        :before-close="handleCloseAdd">
      <el-form :model="categoryFrom" :rules="categoryRules" ref="categoryFrom" label-width="100px">

        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryFrom.categoryName"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAddOrUpdateForm('categoryFrom')">立即{{ dialogTitle }}</el-button>
          <el-button @click="resetForm('categoryFrom')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--  表格操作  -->
    <div class="select-div">

      <el-input
          clearable
          v-model="keywords"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="请输入分类名关键字"
          style="width:200px"
          @keyup.enter.native="searchCategory"
      />

      <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem" @click="searchCategory">
        搜索
      </el-button>

      <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogAdd">新增</el-button>

      <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
                 :disabled="this.selection.length === 0">删除选中
      </el-button>

    </div>

    <!--  表格内容  -->
    <el-table
        :data="tableData"
        border
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="categoryName" label="分类名"></el-table-column>

      <el-table-column prop="createTime" label="创建时间" sortable></el-table-column>

      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="编辑" placement="top-start">
            <el-button circle icon="el-icon-edit" size="mini" @click="handleEdit(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="删除" placement="top-start">
            <el-button circle icon="el-icon-delete" size="mini" type="danger"
                       @click="deleteCheck(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <pagination
        :total="total"
        :page_index="pageNum"
        @pageChange="pageChange"
    />

  </el-card>
</template>

<script>
import { categoryApi } from '@/api';

export default {
  name: "CategoryList",
  data() {
    return {
      tableData: [],
      categoryFrom: {},
      total: 0,
      pageNum: 1,
      pageSize: 10,
      keywords: null,
      selection: [],
      selectedNum: 0,
      dialogAddOrUpdate: false,
      dialogTitle: '',
      categoryRules: {
        categoryName: [
          {required: true, message: '请输入分类名称', trigger: 'blur'}
        ],
      },
    }
  },

  methods: {
    /**
     * input搜索触发事件
     */
    searchCategory() {
      this.pageNum = 1;
      this.loadCategoryList();
    },

    /**
     * 复选框事件
     * @param selection 选中数据数组
     */
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item.id)
      this.selectedNum = selection.length
    },

    /**
     * 分页回调函数
     * @param val
     */
    pageChange(val) {
      this.pageNum = val.pageNum;
      this.pageSize = val.pageSize;
      this.loadCategoryList()
    },

    /**
     * 新增按钮事件
     */
    dialogAdd() {
      this.dialogTitle = "新增";
      this.dialogAddOrUpdate = true;
    },

    /**
     * 编辑按钮触发事件
     * @param id 数据id
     */
    handleEdit(id) {
      categoryApi.getCategoryInfo(id).then((response) => {
        if (response.data.code === 20000) {
          //将当前行角色信息数据回显到弹出表单中，并打开表单
          this.categoryFrom = response.data.data;
          this.dialogTitle = "修改";
          this.dialogAddOrUpdate = true;
        }
      });
    },

    /**
     * 当用户通过点击关闭图标或遮罩关闭 Dialog 时起效的事件
     */
    handleCloseAdd() {
      //关闭Dialog时清空表单
      this.resetForm();
      this.dialogAddOrUpdate = false;
    },

    // 重置弹出框表单内容
    resetForm(formName) {
      if (this.$refs.categoryFrom !== undefined) this.$refs.categoryFrom.resetFields();
      this.categoryFrom = {};
    },

    /**
     * 提交新增/修改表单
     * @param formName
     */
    submitAddOrUpdateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const apiMethod = this.categoryFrom.id ? categoryApi.updateCategory : categoryApi.addCategory;
          apiMethod(this.categoryFrom).then((response) => {
            if (response.data.code === 20000) {
              this.$message({
                showClose: true,
                message: '操作成功！',
                type: 'success',
                onClose: () => {
                  this.loadCategoryList();
                }
              });
            }
          });
          this.dialogAddOrUpdate = false;
          this.resetForm(formName);
        } else {
          alert('请完整填写表单!');
          return false;
        }
      });
    },

    /**
     * 删除数据
     * @param id 数据id
     */
    deleteCheck(id) {
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning"
      }).then(() => {
        const ids = id == null ? this.selection : [id];
        categoryApi.deleteCategories(ids).then((response) => {
          if (response.data.code === 20000) {
            this.$message({
              message: '操作成功！',
              type: 'success'
            });
            this.loadCategoryList();
          }
        });
      }).catch(() => {
        // 取消删除操作
      });
    },


    /**
     * 获取分类列表
     */
    loadCategoryList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        keywords: this.keywords,
      };
      
      categoryApi.getCategoryList(params).then((response) => {
        if (response.data.code === 20000) {
          this.tableData = response.data.data.pagingList;
          this.total = response.data.data.count;
        }
      });
    }
  },

  created() {
    this.loadCategoryList()
  }
}
</script>

<style scoped>

</style>
